package jt.classic.app.info.init;

import jt.classic.system.ISystem;
import jt.classic.system.ISystemException;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.database.SystemDataSourceException;
import jt.classic.system.init.AbstractInitializtion;
import jt.classic.system.lic.params.SignParamsGetter;
import jt.classic.system.lic.util.LicVerify;
import jt.classic.system.role.RoleManager;

import org.dom4j.Document;
import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.limp.basework.SimpleBean4Table;
import org.limp.basework.console.XSystemConfig;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;

import org.limp.mine.DateTrimmer;
import org.limp.mine.StringTool;

import java.io.File;

import java.sql.Connection;

import java.util.List;
import java.util.Map;


/**
 * CMS(version:Basic100)初始化管理器
 *
 * @author mido
 *
 */
public class CMSBasic100Initializtion extends AbstractInitializtion {
    public void load() throws ISystemException {
        SignParamsGetter spg = SignParamsGetter.getInstance();

        spg.load();

        LicVerify lv = new LicVerify();

        Connection conn = null;

        try {
            if (spg.getUserSize() > -1) {
                SystemDataSource ds = SystemDataSource.getInstance();

                conn = ds.getConnection();
            }

            lv.verify("cms100.lic", spg, conn);
        } catch (SystemDataSourceException ex) {
            throw new ISystemException("datasource is invalid, can't check dms-lic",
                ex);
        } catch (ISystemException ex) {
            System.err.println("{========== dms license is invalid ==========}");
            System.err.println("{========== " + spg.getParamsText() +
                "==========}");
            throw new ISystemException(spg.getParamsText(), ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        String syshome = (String) XSystemConfig.config()
                                               .getProperty("XSYSTEM_SYSTEM_HOME");

        String productinit = (String) XSystemConfig.config()
                                                   .getProperty("PRODUCT-LOADING");

        if (productinit.equals("")) {
            System.err.println(
                "system message: invalid parameter 'PRODUCT-LOADING' in xsystem.config.");
        }

        try {
            /* 初始化文件 */
            File file = new File(syshome, productinit);

            if (file.exists()) {
                SystemDataSource ds = SystemDataSource.getInstance();
                conn = ds.getConnection();

                BaseworkUtil util = new BaseworkUtil();

                SAXReader reader = new SAXReader();
                Document document = reader.read(file);

                List moduleList = document.getRootElement().elements("module");

                if ((moduleList != null) && !moduleList.isEmpty()) {
                    for (int i = 0; i < moduleList.size(); i++) {
                        /* xml文件中模块元素 */
                        Element moduleElement = (Element) moduleList.get(i);

                        /* 模块名称 */
                        String mname = StringTool.checkString(moduleElement.attributeValue(
                                    "name"));

                        /* 模块说明 */
                        String mmemo = StringTool.checkString(moduleElement.attributeValue(
                                    "memo"));

                        /* 模块链接 */
                        String murl = StringTool.checkString(moduleElement.attributeValue(
                                    "url"));

                        SimpleBean4Table moduleBean = new SimpleBean4TableImpl(
                                "ISYS_MODULE");
                        moduleBean.getResource().put("mname", mname);
                        moduleBean.getResource().put("mmemo", mmemo);
                        moduleBean.getResource().put("murl", murl);

                        Map info = (Map) util.manualSave1(moduleBean, conn);
                        String mid = (String) info.get("ID");

                        this.initModuleMenu(moduleElement, mid, "0", util, conn);
                    }
                }

                List roleList = document.getRootElement().elements("role");

                if ((roleList != null) && !roleList.isEmpty()) {
                    RoleManager manager = new RoleManager(conn);

                    for (int i = 0; i < roleList.size(); i++) {
                        /* xml文件中模块元素 */
                        Element roleElement = (Element) roleList.get(i);

                        /* 角色可以 */
                        String rkey = StringTool.checkString(roleElement.attributeValue(
                                    "key"));

                        if (!manager.containsRoleKey(rkey)) {
                            /* 角色名称 */
                            String rname = StringTool.checkString(roleElement.attributeValue(
                                        "name"));

                            /* 角色说明 */
                            String rmemo = StringTool.checkString(roleElement.attributeValue(
                                        "memo"));

                            SimpleBean4Table roleBean = new SimpleBean4TableImpl(
                                    "ISYS_ROLE");
                            roleBean.getResource().put("rname", rname);
                            roleBean.getResource().put("rmemo", rmemo);
                            roleBean.getResource().put("rkey", rkey);
                            roleBean.getResource().put("rrv", "1");
                            roleBean.getResource().put("rrvtype", "");
                            roleBean.getResource().put("rrvrating", "0");

                            util.manualSave1(roleBean, conn);
                        }
                    }
                }

                File bakFile = new File(syshome,
                        productinit + ".(" + DateTrimmer.getYMDHMS() + ")bak");

                file.renameTo(bakFile);

                conn.commit();
            }
        } catch (Exception ex) {
            try {
                conn.rollback();
            } catch (Exception ex1) {
                ISystem.catchException(this, ex);
            }

            ISystem.catchException(ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 初始化模块菜单
     *
     * @param menuElement
     * @param mid
     * @param pid
     * @param util
     * @param conn
     */
    private void initModuleMenu(Element parentElement, String mid, String pid,
        BaseworkUtil util, Connection conn) throws Exception {
        List menus = parentElement.elements("menu");

        if ((menus != null) && (menus.size() > 0)) {
            for (int j = 0; j < menus.size(); j++) {
                Element menuElement = (Element) menus.get(j);

                /* 菜单名称 */
                String name = StringTool.checkString(menuElement.attributeValue(
                            "name"));

                /* 菜单说明 */
                String memo = StringTool.checkString(menuElement.attributeValue(
                            "memo"));

                /* 菜单链接 */
                String url = StringTool.checkString(menuElement.attributeValue(
                            "url"));

                SimpleBean4Table menuBean = new SimpleBean4TableImpl(
                        "ISYS_MODULE_MENU");
                menuBean.getResource().put("mnname", name);
                menuBean.getResource().put("mnmemo", memo);
                menuBean.getResource().put("mnurl", url);
                menuBean.getResource().put("mnpid", pid);
                menuBean.getResource().put("mid", mid);

                Map info1 = (Map) util.manualSave1(menuBean, conn);
                String mnid = (String) info1.get("ID");

                if (menuElement.elements("menu").size() > 0) {
                    initModuleMenu(menuElement, mid, mnid, util, conn);
                }
            }
        }
    }
}
